<template>
	<view>
		<!-- <view class="flex text-center text-white text-lg bg">
			<view class="title_btn flex-sub bg" @click="cut(1)" :class="title_color==1?'bgCol2': ''">我的余额
			</view>
			<view class="title_btn flex-sub bg" @click="cut(2)" :class="title_color==2?'bgCol2': ''">我的收益
			</view>
		</view> -->
		<view class="padding">
			<view class="flex  justify-between radius bg ">
				<view class=" u-flex u-p-l-30 u-p-t-30 u-p-b-30">
					<view class="u-m-r-20">
						<u-avatar :src="avatar" size="80"></u-avatar>
					</view>
					<view class="u-flex-1 ">
						<view class="u-font-16 text-white text-bold">{{money}}元</view>
						<view class="u-font-14 u-m-t-10">可用于平台消费</view>
					</view>
				</view>
				<view class="margin-right margin-top-sm" @click="goNav('/my/wallet/mymoneydetail')">钱包明细</view>
			</view>
			<view class="margin-top radius bg flex justify-between flex-wrap padding-lr padding-bottom">
				<view v-for="(item,index) in wallet" :key='index'
					class="flex justify-between padding-sm radius margin-top"
					style="color: #1E1F31;background-color: #F7F7F7; width: 46%;border: 1px solid #F7F7F7;"
					@click="active(item)" :class="{active:item.isSelect}">
					<view>
						{{item.price}}元
						<view class="" v-if="item.giveNum" style="font-size: 24rpx;">
							赠送{{item.giveNum}}张{{item.coupon.money}}元优惠券
						</view>
					</view>
				</view>
			</view>

			<view class="bg margin-top padding-lr radius">
				<view >
					<view style="display: flex;height: 100upx;align-items: center;padding: 20upx 0;"
						v-for="(item,index) in openLists" :key='index'>
						<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
						<view style="font-size: 30upx;margin-left: 20upx;width: 70%;">{{item.text}}
						</view>
						<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item)'>
							<label class="tui-radio">
								<radio color="#1789FD" :checked="openWay === item.id ? true : false" />
							</label>
						</radio-group>
					</view>
				</view>
			</view>

			<view class="btn" @click="pay">确认支付</view>
		</view>


		<view class="flex justify-around margin-top text-white">
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title_color: 1,
				money: 0,
				avatar: '',
				Profit: 0,
				openLists: [{
					image: '../static/zhifubao.png',
					text: '支付宝',
					id: 1
				}, {
					image: '../static/icon_weixin.png',
					text: '微信',
					id: 2
				}],
				openWay: 1,
				wallet: [],
				moneyNum: null,
				thisSelect: {},
				charge: 0, //提现手续费
				maxMoney: 0, //最高提现额度
				minMoney: 0, //最低提现额度
				ratio: '', //金元比例
				placeholder: '',
				sp:0
			}
		},
		onLoad() {
			this.avatar = uni.getStorageSync('avatar')

			// #ifdef APP-PLUS
			this.openLists = [{
				image: '../../static/images/my/zhifubao.png',
				text: '支付宝',
				id: 1
			}, {
				image: '../../static/images/my/icon_weixin.png',
				text: '微信',
				id: 2
			}];
			this.openWay = 1;
			// #endif

			// #ifdef MP-WEIXIN
			this.openLists = [{
				image: '../../static/share/icon_weixin.png',
				text: '微信',
				id: 2
			}];
			this.openWay = 2;
			// #endif
			
			// #ifdef H5
			let ua = navigator.userAgent.toLowerCase();
			if (ua.indexOf('micromessenger') !== -1) {
				this.openLists = [{
					image: '../../static/share/icon_weixin.png',
					text: '微信',
					id: 2
				},{
					image: '../../static/images/my/zhifubao.png',
					text: '支付宝',
					id: 1
				}];
				this.openWay = 1;
			}else{
				this.openLists = [{
					image: '../../static/images/my/zhifubao.png',
					text: '支付宝',
					id: 1
				}];
				this.openWay = 1;
			}
			
			// #endif
		},
		onShow() {
			this.getMoney()
			this.getCharge()
			this.getMinMoney()
			this.getMaxMoney()
			this.getRatio()
			this.getUserInfo()
			this.getMoneyPage();
		},
		methods: {
			//获取充值配置
			getMoneyPage(){
				this.$Request.get("/app/payClassify/selectPayClassifyList").then(res => {
					if (res.code == 0) {
						res.data.map((item,index)=>{
							if(index==0){
								item.isSelect = true
							}else{
								item.isSelect = false
							}
						})
						this.wallet = res.data
						this.thisSelect = res.data[0]
					}
				});
			},
			getUserInfo() {
				this.$Request.get("/app/user/selectUserById").then(res => {
					if (res.code == 0) {
						this.avatar = res.data.avatar?res.data.avatar: '../../static/logo.png'
						uni.setStorageSync('avatar', res.data.avatar)
					}
				});
			},
			// 提现手续费
			getCharge() {
				this.$Request.get("/app/common/type/152").then(res => {
					if (res.code == 0) {
						this.charge = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 最低提现额度
			getMinMoney() {
				this.$Request.get("/app/common/type/112").then(res => {
					if (res.code == 0) {
						this.minMoney = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 最高提现额度
			getMaxMoney() {
				this.$Request.get("/app/common/type/153").then(res => {
					if (res.code == 0) {
						this.maxMoney = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 金元比例
			getRatio() {
				this.$Request.get("/app/common/type/154").then(res => {
					if (res.code == 0) {
						this.ratio = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
						this.wallet.forEach(re => {
							re.num = re.price * res.data.value
						})
					}
				});
			},
			cut(e) {
				this.title_color = e
			},
			goNav(url) {
				uni.navigateTo({
					url
				})
			},
			active(e) {
				this.wallet.map(item=>{
					if (item.payClassifyId == e.payClassifyId) {
						item.isSelect = true
						this.thisSelect = e
					} else {
						item.isSelect = false
					}
				})
			},
			// 我的余额
			getMoney() {
				this.$Request.get("/app/userMoney/selectMyMoney").then(res => {
					if (res.code == 0 && res.data) {
						console.log(res.data.money)
						this.money = res.data.money
					}
				});
			},
			selectWay: function(item) {
				this.openWay = item.id;
			},

			pay() {
				let that = this
				let data = {
					money: that.thisSelect.price
				}
				console.log(data)
				// 获取订单编号
				that.$Request.post("/app/appOrder/insertOrder", data).then(res => {
					console.log(res, '********')
					uni.showLoading({
						title: '支付中...'
					});
					if (res.code == 0) {
						// this.Profit = res.data
						if (that.openWay == 2) {
							// #ifdef APP-PLUS
							let datawa = {
								orderId:res.data.id,
								payClassifyId:this.thisSelect.payClassifyId
							}
							// 微信APP支付 根据订单id获取支付信息
							that.$Request.post("/app/wxPay/payAppOrder", datawa).then(ret => {
								console.log(ret,'retretretretretret')
								that.isCheckPay(ret.code, 'wxpay', JSON.stringify(ret.data));
							});
							// #endif

							// #ifdef MP-WEIXIN
							// 微信小程序支付
							let datawx ={
								orderId:res.data.id,
								payClassifyId:this.thisSelect.payClassifyId
							}
							that.$Request.post('/app/wxPay/wxPayJsApiOrder',datawx).then(ret => {
								uni.hideLoading()
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: ret.data.timestamp,
									nonceStr: ret.data.noncestr,
									package: ret.data.package,
									signType: ret.data.signType,
									paySign: ret.data.sign,
									success: function(suc) {
										console.log('success:' + JSON.stringify(suc));
										uni.showToast({
											title: '支付成功',
											icon: 'success'
										})
										setTimeout(d => {
											uni.navigateBack(1)
										}, 1000);
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										uni.showToast({
											title: '支付失败',
											icon: 'none'
										})
									}
								});
							});
							// #endif
							
							// #ifdef H5
							let ua = navigator.userAgent.toLowerCase();
							console.log(ua)
							if (ua.indexOf('micromessenger') !== -1) {
								let data = {
									orderId:res.data.id,
									payClassifyId:this.thisSelect.payClassifyId
								}
								that.$Request.post('/app/wxPay/wxPayMpOrder',data).then(res => {
									if (res.code == 0) {
										that.callPay(res.data);
									} else {
										uni.showToast({
											icon: 'none',
											title: '支付失败!'
										});
									}
								});
							} 
							// #endif
							
						} else {
							// #ifdef H5
							let data = {
								orderId:res.data.id,
								classify:2,
								payClassifyId:this.thisSelect.payClassifyId
							}
							that.$Request.post('/app/aliPay/payMoneyOrder',data).then(
							res => {
								if (res.code === 0) {
									const div = document.createElement('div')
									div.innerHTML = res.data
									document.body.appendChild(div)
									document.forms[0].submit()
								} else {
									uni.showToast({
										icon: 'none',
										title: '支付失败!'
									});
								}
							});
							// #endif
							// #ifdef APP
							// APP支付宝支付
							let dataz = {
								orderId:res.data.id,
								classify:1,
								payClassifyId:this.thisSelect.payClassifyId
							}
							that.$Request.post("/app/aliPay/payMoneyOrder",dataz).then(ret => {
								console.log(ret)
								that.isCheckPay(ret.code, 'alipay', ret.data);
							});
							// #endif
						}
					}
				});
			},
			callPay: function(response) {
				if (typeof WeixinJSBridge === "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
					}
				} else {
					this.onBridgeReady(response);
				}
			},
			onBridgeReady: function(response) {
				let that = this;
				if (!response.package) {
					return;
				}
				console.log(response,'++++++++')
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						console.log(res,'/*-/*-/*-')
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							uni.showLoading({
								title: '支付成功'
							});
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							uni.hideLoading();
						}
						WeixinJSBridge.log(response.err_msg);
					}
				);
			},
			isCheckPay(status, name, order) {
				if (status == 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误',
						icon: 'none'
					});
				}
			},
			setPayment(name, order) {
				console.log('*-*-*')
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					success: function(res) {
						console.log(res)
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			// 提现
			cashMoney() {
				if (!this.moneyNum) {
					uni.showToast({
						icon: 'none',
						title: '请输入提现金额'
					})
					return
				}
				if (this.moneyNum > this.money * 1) {
					uni.showToast({
						icon: 'none',
						title: '您的余额不足'
					})
					return
				}
				// if (this.moneyNum*1+this.charge*this.moneyNum > this.money*1) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '您的手续费不足'
				// 	})
				// 	return
				// }

				let zhiFuBao = uni.getStorageSync('zhiFuBao')
				let zhiFuBaoName = uni.getStorageSync('zhiFuBaoName')

				if (!zhiFuBao && !zhiFuBaoName) {
					uni.navigateTo({
						url: '/my/wallet/zhifubao'
					})
					return
				}

				let that = this
				that.sp = (that.moneyNum*this.charge).toFixed(2)
				uni.showModal({
					title: '提示',
					content: '本次提现'+that.moneyNum+'元，服务费'+this.sp +'元，是否确认提现？',
					success: function(res) {
						if (res.confirm) {
							that.$Request.get("/app/cash/cashMoney", {
								money: that.moneyNum
							}).then(res => {
								if (res.code == 0) {
									uni.showToast({
										icon: 'none',
										title: res.msg
									})
									that.moneyNum = null
								} else {
									uni.showToast({
										icon: 'none',
										title: res.msg
									})
								}
								that.getMoney()
							});
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background-color: #F7F7F7;
	}
.bgCol2{
	color: #557EFD;
}
	.bg {
		background-color: #FFFFFF;
	}
	.active {
		border: 1px solid #557EFD !important;
		color: #557EFD !important;
		box-sizing: border-box;
	}

	.title_btn {
		height: 78upx;
		line-height: 78upx;
		/* background: #f7f7f7; */
	}

	.btn {
		width: 100%;
		height: 88upx;
		background: #557EFD;
		border-radius: 44upx;
		text-align: center;
		line-height: 88upx;
		margin-top: 40upx;
		font-size: 28upx;
		color: #FFF;
	}
</style>
